#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:set sts=4:tabstop=4:expandtab:shiftwidth=4:
# EasyUbuntu - Install commonly requested apps on your (k/X)ubuntu box 
# Copyright (C) 2006 EasyUbuntu team
# https://launchpad.net/products/easyubuntu
# http://easyubuntu.freecontrib.org
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA 02111-1307 USA
# 
from backend import *
from detect import *
from gtkprocess import gtkLogger

import gtk, gtk.glade
import os
import sys
from xml.dom import minidom

def scan_installed(desc, packagelist, configlist, all_pack_list, confdir):
    """
    Check if packages and/or configurations are installed
    """

    if packagelist == [] and len(configlist) != 0:
        # We should check the repos list here
        return False

    Installed = True

    for s in packagelist:
        if all_pack_list.find(',' + s + ',') == -1:
            Installed = False

    return Installed

class MainWindow:
    def __init__(self, pkglist, desktop, datadir, confdir):
        self.datadir = datadir
        self.confdir = confdir
        self.packageslist = [] #list of packages to be installed
        self.configslist = []  #list of configuration to be performed
        
        self.tree = gtk.glade.XML(os.path.join(self.datadir, 'easyubuntu.glade'), 'mainwindow')
        signals = {}
        for attr in dir(self):
            signals[attr] = getattr(self, attr)
        self.tree.signal_autoconnect(signals)

        #load icon and logo
        try:
            self.logo = gtk.gdk.pixbuf_new_from_file(os.path.join(self.datadir, 'easyubuntu.svg'))
        except :
            self.logo = gtk.gdk.pixbuf_new_from_file(os.path.join(self.datadir, 'easyubuntu.png'))
        self.tree.get_widget('logo').set_from_pixbuf(self.logo)

        self.icon = gtk.gdk.pixbuf_new_from_file(os.path.join(self.datadir, 'easyubuntu.png'))
        self.tree.get_widget('mainwindow').set_icon(self.icon)
        dynamic_area = self.tree.get_widget('dynamic_area')
        notebook = gtk.Notebook()
        dynamic_area.add(notebook)

        # Generate a list of all installed packages in the system
        pack_list_proc = os.popen("dpkg --get-selections | grep -v deinstall", "r")
        pack_list_seq = pack_list_proc.read()
        pack_list_proc.close()

        # Format and compact the list
        all_pack_list = "".join(pack_list_seq)
        all_pack_list = all_pack_list.replace("install", ",")
        all_pack_list = all_pack_list.replace(" ", "")
        all_pack_list = all_pack_list.replace("\t", "")
        all_pack_list = all_pack_list.replace("\n", "")
        all_pack_list = " , " + all_pack_list + ","

        # Assume that nothing is installed. If something was, then we will have to explain the checkboxes
        found_installed = False

        #every <category> in the XML is a tab in the notebook
        catlist = childNodeWithAttrs(pkglist, desktop)[0]
        for catname in catlist:
            label = gtk.Label(catname.title())
            vbox = gtk.VBox()
            notebook.append_page(vbox, label)
            #every <subcat> in the XML is a checkbox in the page
            subcatlist = childNodeWithAttrs(pkglist,desktop, catname)[0]
            for subcatname in subcatlist:
                if subcatname != "N/A":
                    desc = childNodeWithAttrs(pkglist, desktop,catname,subcatname,'label')[0]
                    packagelist = childNodeWithAttrs(pkglist,desktop,catname,subcatname,'pkg')[0]
                    configlist = childNodeWithAttrs(pkglist,desktop,catname,subcatname,'config')[0]
                    #print catname,subcatname,desc
                    check = gtk.CheckButton(desc[0])

                    if scan_installed(desc[0], packagelist, configlist, all_pack_list, confdir) == True:
                        check.set_active(True)
                        check.set_sensitive(False) # You cannot uninstall!
                        found_installed = True
                    else:
                        check.connect("toggled", self.on_dynamic_checkbox_toggled, packagelist, configlist)

                    vbox.pack_start(check, False, False, 0)

        if found_installed:
            msgbox = gtk.MessageDialog(type=gtk.MESSAGE_INFO, buttons=gtk.BUTTONS_OK, message_format="Previously installed components have been detected. Note that EasyUbuntu CANNOT uninstall them; therefore, their checkboxes are disabled (grayed out).")
            msgbox.run()
            msgbox.destroy()

        self.tree.get_widget('mainwindow').show_all()

    def run(self):
        gtk.main()

    def on_mainwindow_destroy(self, widget, data = None):
        gtk.main_quit()
    
    def on_cancel_button_clicked(self, gui):
        gtk.main_quit()
    
    def on_about_button_clicked(self, gui):
        tree = gtk.glade.XML(os.path.join(self.datadir, 'easyubuntu.glade'), 'aboutdialog')
        dialog = tree.get_widget('aboutdialog')
        dialog.set_logo(self.logo)
        dialog.set_icon(self.icon)
        dialog.show()
    
    def on_dynamic_checkbox_toggled(self, widget, packages = None, configs = None):
        if widget.get_active():
            self.packageslist.extend(packages)
            self.configslist.extend(configs)
        else:
            for eachpackage in packages:
               self.packageslist.remove(eachpackage)
            
            for eachconfig in configs:
               self.configslist.remove(eachconfig)

        if len(self.packageslist) or len(self.configslist):
            self.tree.get_widget('ok_button').set_sensitive(True)
        else:
            self.tree.get_widget('ok_button').set_sensitive(False)
        return False # permit checkbox to actually be toggled

    def on_ok_button_clicked(self, gui):
        self.tree.get_widget('mainwindow').hide()
        
        logger = gtkLogger(self.packageslist, self.configslist, self.confdir)

        self.tree.get_widget('mainwindow').show()
        self.tree.get_widget('ok_button').set_sensitive(False)


def apt_running():
    msgbox = gtk.MessageDialog(type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_OK_CANCEL, \
    message_format="Another package manager is running. Please close the package manager and" \
" press the OK button. If you would like to use the other package manager," \
" press Cancel to exit EasyUbuntu.")
    response = msgbox.run()
    if response == gtk.RESPONSE_OK:
        msgbox.destroy()
        return True
    else:
        return False
    
def launcher(datadir, confdir):
    if aptcheck():
        pressed_ok = apt_running()
        if not pressed_ok: sys.exit(1)
#    pkglist = minidom.parse(os.path.join(datadir, 'packagelist-%s.xml' % codename()))
    pkglist = minidom.parse(os.path.join(datadir, 'packagelist.xml'))
    ui = MainWindow(pkglist, de(), datadir, confdir)
    ui.run()

if __name__ == '__main__':
    confdir = os.path.abspath('./conf')
    datadir = os.path.abspath('.')
    launcher(datadir, confdir)
